package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"zg2_zy/zy11_cart/cartRpc/models"
	"zg2_zy/zy11_cart/cartRpc/pkg"

	"zg2_zy/zy11_cart/cartRpc/cart"
	"zg2_zy/zy11_cart/cartRpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrdersLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrdersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrdersLogic {
	return &CreateOrdersLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrdersLogic) CreateOrders(in *cart.CreateOrdersRequest) (*cart.CreateOrdersResponse, error) {
	// todo: add your logic here and delete this line

	var err error

	var g models.Goods
	var o models.Order

	o.UserID = in.UserId
	g.ID = uint(in.GoodsId)

	if err = g.GetGoodsById(); err != nil {
		return nil, errors.New("<商品信息获取失败>")
	}

	o.GoodsId = in.GoodsId
	o.OrderSn = uuid.NewString()
	o.PayType = in.PayType
	o.Status = in.Status
	o.Num = in.Num
	o.Total = g.GoodsPrice * float64(in.Num)

	if err = o.Create(); err != nil {
		return nil, errors.New("订单创建失败")
	}

	g.Stock -= in.Num

	amount := fmt.Sprintf("%.2f", o.Total)

	url := pkg.AliPay(amount, o.OrderSn)

	return &cart.CreateOrdersResponse{
		OrderSn: o.OrderSn,
		PayUrl:  url,
	}, nil
}
